#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "WaterMarkGenerator/PictureDateExtracter.h"

#include <QMessageBox>
#include <QFileDialog>

#include <QImage>
#include <QPixmap>

#include <QDebug>

#include <QFile>
#include <QFileInfo>

#include <QDateTime>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

//    this->grabGesture(Qt::PanGesture);
    this->grabGesture(Qt::PinchGesture);
//    this->grabGesture(Qt::SwipeGesture);

//    connect(ui->slider_bottompercent, &QSlider::sliderMoved, this, [&](){
//        this->_update_watermask();
//    });
//    connect(ui->slider_leftpercent, &QSlider::sliderMoved, this, [&](){
//        this->_update_watermask();
//    });

    constexpr static const int count_max = 2;

    connect(ui->scrollbar_fromup, &QScrollBar::valueChanged, this, [&](){
        static int count = 0;
        ++count;
        if (count < count_max) return;

        count = 0;
        this->_update_watermask();
    });
    connect(ui->scrollbar_fromleft, &QScrollBar::valueChanged, this, [&](){
        static int count = 0;
        ++count;
        if (count < count_max) return;

        count = 0;
        this->_update_watermask();
    });
}


//! [swipe function]
//void MainWindow::swipeTriggered(QSwipeGesture *gesture)
//{
//    qDebug() << "swiped";
//    if (gesture->state() == Qt::GestureFinished) {
//        if (gesture->horizontalDirection() == QSwipeGesture::Left
//            || gesture->verticalDirection() == QSwipeGesture::Up) {
//            qDebug() << ( "swipeTriggered(): swipe to Left Up" );
//        } else {
//            qDebug() << ( "swipeTriggered(): swipe to Right Down" );
//        }
//    }
//}

void MainWindow::pinchTriggered(QPinchGesture *gesture)
{
    static uint64_t count = 0; // 过滤

    if (generator_.isNull()) return;

    QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags();

    if (gesture->state() == Qt::GestureFinished) {
        count = 0;
        this->_update_watermask();
        return;
    }

    if (changeFlags & QPinchGesture::ScaleFactorChanged) {
        ++count;
        if (count < 10) { // 缩放灵敏度, 越大越不灵敏, 但是不容易卡顿
            return;
        }

        auto factor = gesture->scaleFactor();

        font_size_ = font_size_ * factor;
        if (font_size_ < 0.1) font_size_ = 0.1;
        if (font_size_ > 10.0) font_size_ = 10.0;

//        qDebug() << "pinchTriggered" << "ScaleFactorChanged" << factor << font_size_;
        this->_update_watermask();

        count = 0;
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

//void MainWindow::panTriggered(QPanGesture *gesture)
//{
////#ifndef QT_NO_CURSOR
////    switch (gesture->state()) {
////    case Qt::GestureStarted:
////    case Qt::GestureUpdated:
////        setCursor(Qt::SizeAllCursor);
////        break;
////    default:
////        setCursor(Qt::ArrowCursor);
////    }
////#endif
//    QPointF delta = gesture->delta();
//    qDebug() << "panTriggered():" << delta;
////    horizontalOffset += delta.x();
////    verticalOffset += delta.y();
//}


void MainWindow::on_pb_load_clicked()
{
    loaded_filename_ = QFileDialog::getOpenFileName(this);
    if (loaded_filename_.isEmpty() || loaded_filename_.isNull())
    {
        return;
    }

    qDebug() << tr("读取文件%0").arg(loaded_filename_);
    // QMessageBox::information(this, tr("读取文件"), tr("读取文件%0").arg(loaded_filename_));

    try {
        original_image_loaded_ = QImage(loaded_filename_);
        generator_ = WaterMarkGenerator(loaded_filename_);
    } catch (WaterMarkGeneratorException& we) {
        QMessageBox::warning(this, tr("读取文件"), tr("无效的图片文件%0, 错误:%1").arg(loaded_filename_).arg(we.what()));
        return;
    } catch (...) {
        QMessageBox::warning(this, tr("读取文件"), tr("无效的图片文件%0, 未知错误").arg(loaded_filename_));
        return;
    }

    this->font_size_ = 1.57;

    _update_watermask();
}


void MainWindow::on_pb_save_clicked()
{
    if (generator_.isNull()) {
        QMessageBox::warning(this, tr("保存文件"), tr("保存文件失败, 未生成水印"));
        return;
    }

    auto save_filename = _get_save_filename(loaded_filename_);

    QFile file(save_filename);
    file.open(QIODevice::ReadWrite);

    if (!file.isOpen()) {
        QMessageBox::warning(this, tr("保存文件"), tr("error saving %0").arg(save_filename));
    }

    file.close();

    if (!displaying_image_.save(save_filename, "jpg", 100)) {
        QMessageBox::warning(this, tr("保存文件"), tr("保存文件%0失败, 无权限").arg(save_filename));
        return;
    } else {
        QMessageBox::information(this, tr("保存文件"), tr("保存文件%0成功").arg(save_filename));
    }
}

void MainWindow::_update_watermask()
{
    if (generator_.isNull()) {
        return;
    }

    generator_.setPosSize(_get_pos_size_disc_from_ui());

    try {
        displaying_image_ = generator_.getWaterMarkedImage(PictureDateExtracter::getLastModifyTimeStringOfFile(loaded_filename_));
    } catch (WaterMarkGeneratorException& we) {
        QMessageBox::warning(this, tr("读取文件"), tr("生成水印失败, 错误信息:%0").arg(we.what()));
        return;
    } catch (...) {
        QMessageBox::warning(this, tr("读取文件"), tr("生成水印失败, 未知异常"));
        return;
    }

    QPixmap pixmap = QPixmap::fromImage(displaying_image_).scaled(ui->lb_pic->size(),
                                                      Qt::KeepAspectRatio,
                                                      Qt::SmoothTransformation);

    ui->lb_pic->setPixmap(pixmap);

    ui->lb_pic->setAlignment (Qt::AlignCenter);

    //    ui->slider_bottompercent->resize(pixmap.width(), ui->slider_bottompercent->height());
}

QString MainWindow::_get_save_filename(const QString &ori_filename)
{
    QString save_filename;
//#if defined(Q_OS_WIN32) || defined(Q_OS_WIN64) || defined(Q_OS_LINUX)
//    save_filename = ori_filename + "_watermark_";
//#elif defined(Q_OS_ANDROID)
    save_filename = "/storage/emulated/0/DCIM/Camera/watermark_";
//#else
//    save_filename = ori_filename + "_watermark_";
//#endif

    QString unique_str = QString::number(QDateTime::currentMSecsSinceEpoch());

    save_filename = save_filename + unique_str + ".jpg";

    return save_filename;
}

WaterMarkGenerator::PosSizeDisc MainWindow::_get_pos_size_disc_from_ui() const
{
//    return {static_cast<double>(ui->slider_bottompercent->value())       / 100.0,
//            static_cast<double>(9999 - ui->slider_leftpercent->value())  / 100.0,
//            this->font_size_};
//    return {this->percent_from_bottom,
//            this->percent_from_right,
//            this->font_size_};
    return {static_cast<double>(ui->scrollbar_fromup->maximum() - ui->scrollbar_fromup->value()),
            static_cast<double>(ui->scrollbar_fromleft->maximum() - ui->scrollbar_fromleft->value()),
            this->font_size_};
}

